﻿using System;
using System.Linq;
using System.Data.SqlServerCe;
using gbL.NetBoard.Helpers;
using gbL.NetBoard.Examples.DoubleMVC.View.Data.Requests;
using System.Reflection;
using System.IO;

namespace gbL.NetBoard.Examples.DoubleMVC.View.Data
{
    class OrderDetailsTableView : MultiTypedMessageListener
    {
        public OrderDetailsTableView(Blackboard domain) : base(domain) { }

        protected override void OnMessageAdded(object message)
        {
            if (message is OrderDetailRowRequest) Process((OrderDetailRowRequest)message);
        }

        protected override void OnMessageRemoved(object message)
        {
            //
        }

        protected override Type[] MessageTypes
        {
            get { return new[] { typeof(OrderDetailRowRequest) }; }
        }

        void Process(OrderDetailRowRequest message)
        {
            var taken = Messages.Take(x => x.Message == message);
            if (taken.Count == 0) return;

            message.Results = new System.Data.DataTable();

            string SQL = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "gbL.NetBoard.Examples.DoubleMVC.View.Data.Queries.OrderDetailsList.query"
            )).ReadToEnd();
            if (message.OrderID != default(int))
            {
                SQL += string.Format(" WHERE od.[Order ID] = {0}", message.OrderID);
            }
            SQL += " ORDER BY od.[Product ID]";

            using (SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.NorthwindConnectionString))
            {
                cnn.Open();
                SqlCeCommand cmd = new SqlCeCommand(SQL, cnn);
                SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
                da.Fill(0, 999999, message.Results);
                cnn.Close();
            }
        }
    }
}
